package com.sinosoft.cloud.access.codec;

import com.sinosoft.cloud.access.net.MessageObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.apachecommons.CommonsLog;

import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.List;

/**
 * cloud-netty
 *
 * @title: cloud-netty
 * @package: com.sinosoft.cloud.access.net
 * @author: yangming
 * @date: 2017/12/2 下午2:26
 */
@CommonsLog
public class AccessDecoder extends AbstractAccessDecoder {
    private DecoderFactory decoderFactory = DecoderFactory.getInstance();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        MessageObject decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
    }

    private MessageObject decode(ChannelHandlerContext ctx, ByteBuf in) {

//        log.info("AccessDecoder收到:" + in);
        Decoder decoder = decoderFactory.getDecoder(getAccessName());
        if (decoder == null) {
            return null;
        }

        in.order(ByteOrder.BIG_ENDIAN);
        String x = in.toString(Charset.defaultCharset());
        int frameLengthInt = decoder.getBodySize(x) + decoder.getHeadSize(x);
        int currentMsgLength = in.readableBytes();
        if (currentMsgLength < frameLengthInt) {
            return null;
        }
        MessageObject messageObject = new MessageObject(x);
        int readerIndex = in.readerIndex();
        in.readerIndex(readerIndex + frameLengthInt);
        log.info("接收到的原始消息为：" + messageObject.getOriginalMsg());
        return messageObject;
    }
}
